/**
 * Shoplus API 调试测试
 * 用于诊断API连接问题
 */

const axios = require('axios');
const shoplusService = require('./src/services/shoplusService');

/**
 * 测试基本连接
 */
async function testBasicConnection() {
  console.log('=== 测试基本连接 ===');
  
  try {
    const response = await axios.get('https://www.shoplus.net', {
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
      }
    });
    
    console.log('✅ 基本连接成功');
    console.log('状态码:', response.status);
    console.log('响应头:', Object.keys(response.headers));
    
  } catch (error) {
    console.log('❌ 基本连接失败:', error.message);
  }
}

/**
 * 测试API端点
 */
async function testAPIEndpoint() {
  console.log('\n=== 测试API端点 ===');
  
  try {
    const url = 'https://www.shoplus.net/api/v1/product/search';
    
    // 不带认证的请求，看看返回什么
    const response = await axios.get(url, {
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
      },
      validateStatus: () => true // 接受所有状态码
    });
    
    console.log('状态码:', response.status);
    console.log('响应类型:', typeof response.data);
    
    if (typeof response.data === 'string') {
      console.log('响应内容（前200字符）:', response.data.substring(0, 200));
    } else {
      console.log('响应数据:', response.data);
    }
    
  } catch (error) {
    console.log('❌ API端点测试失败:', error.message);
  }
}

/**
 * 测试认证token格式
 */
async function testTokenFormat() {
  console.log('\n=== 测试认证token格式 ===');
  
  const authToken = {
    "name": "13143359181",
    "expires": 1757322261597,
    "accessToken": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJhY2NvdW50TnVtYmVyXCI6XCIxMzE0MzM1OTE4MVwiLFwiYWNjb3VudFR5cGVcIjowLFwiYXBwbHlTdGF0dXNcIjoyLFwiYnVzaW5lc3NUeXBlXCI6MixcImZyb21TeXN0ZW1cIjoxMyxcImlkXCI6NTQwMTUyLFwiaXNFeHBpcmVcIjpmYWxzZSxcImp3dElkXCI6XCI5NDRjMmM2NTdhNTQ0ODJkOWRkMzRkM2Q3YmI2ZDc4OFwiLFwibG9naW5OYW1lXCI6XCIxMzE0MzM1OTE4MVwiLFwibWVyY2hhbnRJZFwiOjUzMTU0OCxcInByb2ZpbGVcIjpcImdjcF91c193ZXN0MVwiLFwic3lzdGVtSWRcIjo4LFwidG9rZW5FeHBpcmVEYXRlXCI6MTc1NzMyMjI2MTQwNyxcIndlY2hhdFN1YlwiOmZhbHNlfSIsImlzcyI6Inp6LXNhYXMtcGVyaW1zc2lvbiIsImlhdCI6MTc1NjcxNzQ2MSwianRpIjoiOTQ0YzJjNjU3YTU0NDgyZDlkZDM0ZDNkN2JiNmQ3ODgifQ.AGhNKdNQfUi7FoxHBgiL33157ls6y8zUfmk-G585rX8",
    "userId": 540152,
    "phone": "13143359181",
    "locale": "en"
  };
  
  console.log('Token过期时间:', new Date(authToken.expires));
  console.log('当前时间:', new Date());
  console.log('Token是否过期:', Date.now() > authToken.expires);
  
  const encodedToken = encodeURIComponent(JSON.stringify(authToken));
  console.log('编码后token长度:', encodedToken.length);
  console.log('编码后token（前100字符）:', encodedToken.substring(0, 100));
}

/**
 * 测试不同的请求方式
 */
async function testDifferentMethods() {
  console.log('\n=== 测试不同的请求方式 ===');
  
  const authToken = {
    "name": "13143359181",
    "expires": 1757322261597,
    "accessToken": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJhY2NvdW50TnVtYmVyXCI6XCIxMzE0MzM1OTE4MVwiLFwiYWNjb3VudFR5cGVcIjowLFwiYXBwbHlTdGF0dXNcIjoyLFwiYnVzaW5lc3NUeXBlXCI6MixcImZyb21TeXN0ZW1cIjoxMyxcImlkXCI6NTQwMTUyLFwiaXNFeHBpcmVcIjpmYWxzZSxcImp3dElkXCI6XCI5NDRjMmM2NTdhNTQ0ODJkOWRkMzRkM2Q3YmI2ZDc4OFwiLFwibG9naW5OYW1lXCI6XCIxMzE0MzM1OTE4MVwiLFwibWVyY2hhbnRJZFwiOjUzMTU0OCxcInByb2ZpbGVcIjpcImdjcF91c193ZXN0MVwiLFwic3lzdGVtSWRcIjo4LFwidG9rZW5FeHBpcmVEYXRlXCI6MTc1NzMyMjI2MTQwNyxcIndlY2hhdFN1YlwiOmZhbHNlfSIsImlzcyI6Inp6LXNhYXMtcGVyaW1zc2lvbiIsImlhdCI6MTc1NjcxNzQ2MSwianRpIjoiOTQ0YzJjNjU3YTU0NDgyZDlkZDM0ZDNkN2JiNmQ3ODgifQ.AGhNKdNQfUi7FoxHBgiL33157ls6y8zUfmk-G585rX8",
    "userId": 540152,
    "phone": "13143359181",
    "locale": "en"
  };
  
  const encodedToken = encodeURIComponent(JSON.stringify(authToken));
  const url = 'https://www.shoplus.net/api/v1/product/search';
  
  // 方法1: GET请求带参数
  console.log('\n--- 方法1: GET请求 ---');
  try {
    const response = await axios.get(url, {
      params: {
        cursor: 0,
        keyword: 'test',
        is_commerce: false,
        sort: 71,
        sort_type: 'DESC'
      },
      headers: {
        'authorized-token': encodedToken,
        'Accept': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
      },
      timeout: 10000,
      validateStatus: () => true
    });
    
    console.log('GET请求状态:', response.status);
    console.log('GET请求响应类型:', typeof response.data);
    
    if (typeof response.data === 'string' && response.data.includes('<!doctype html>')) {
      console.log('❌ GET请求返回HTML错误页面');
    } else {
      console.log('✅ GET请求返回JSON数据');
      console.log('响应数据:', response.data);
    }
    
  } catch (error) {
    console.log('❌ GET请求失败:', error.message);
  }
  
  // 方法2: POST请求
  console.log('\n--- 方法2: POST请求 ---');
  try {
    const response = await axios.post(url, {
      cursor: 0,
      keyword: 'test',
      is_commerce: false,
      sort: 71,
      sort_type: 'DESC'
    }, {
      headers: {
        'authorized-token': encodedToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
      },
      timeout: 10000,
      validateStatus: () => true
    });
    
    console.log('POST请求状态:', response.status);
    console.log('POST请求响应类型:', typeof response.data);
    
    if (typeof response.data === 'string' && response.data.includes('<!doctype html>')) {
      console.log('❌ POST请求返回HTML错误页面');
    } else {
      console.log('✅ POST请求返回JSON数据');
      console.log('响应数据:', response.data);
    }
    
  } catch (error) {
    console.log('❌ POST请求失败:', error.message);
  }
}

/**
 * 测试Shoplus服务
 */
async function testShoplusService() {
  console.log('\n=== 测试Shoplus服务 ===');
  
  try {
    const result = await shoplusService.searchProducts('test');
    
    console.log('服务调用结果:');
    console.log('成功:', result.success);
    console.log('错误:', result.error);
    console.log('消息:', result.message);
    
    if (result.data) {
      console.log('数据长度:', result.data.length);
    }
    
  } catch (error) {
    console.log('❌ 服务调用失败:', error.message);
  }
}

/**
 * 主函数
 */
async function main() {
  console.log('🔍 Shoplus API 调试测试');
  console.log('=' .repeat(50));
  
  await testBasicConnection();
  await testAPIEndpoint();
  await testTokenFormat();
  await testDifferentMethods();
  await testShoplusService();
  
  console.log('\n' + '='.repeat(50));
  console.log('🎯 调试测试完成');
}

// 运行测试
if (require.main === module) {
  main().catch(console.error);
}

module.exports = {
  testBasicConnection,
  testAPIEndpoint,
  testTokenFormat,
  testDifferentMethods,
  testShoplusService
};